package com.ysucode.web.websocket;

import com.ysucode.pojo.User;
import com.ysucode.service.UserService;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

//@Component
@ServerEndpoint("/matchWebSocket/{id}")

public class MatchWebSocket {
    //初始化user服务
    private UserService userService = new UserService();

    //用户id
    private String id;

    //匹配状态 初始化0代表未进行匹配 1代表正在匹配 2代表匹配完成进入pk
    private String status;

    //该用户的对手id
    private String rivalId;

    //每个客户端自己的session
    private Session session;

    //所有进入联机大厅的用户
    private static ConcurrentHashMap<String, MatchWebSocket> concurrentHashMap = new ConcurrentHashMap<>();

    //联机大厅客户端数量
    private static int onlineCount = 0;

    //匹配池中的用户
    private static ConcurrentHashMap<String, MatchWebSocket> matchingHashMap = new ConcurrentHashMap<>();

    @OnMessage
    public void onMessage(String message, Session session) throws IOException, InterruptedException {
        //打印客户端消息
        System.out.println("前端传来的信息为：" + message);
        //System.out.println("status：" + status);

        if ("double".equals(message) && "0".equals(status)) { //匹配双人比赛
            //更改用户状态为1
            status = "1";

            //将该用户加入匹配池
            matchingHashMap.put(id, this);

            //返回客户端信息 匹配中
            session.getBasicRemote().sendText("matchingDouble");

            //每隔五秒在匹配池中进行一次轮询
            while (true) {
                System.out.println(id + "新一轮的匹配搜寻");
                Thread.sleep(5000);
                if (status == "2") { //如果该用户被其他用户先匹配到 则退出匹配
                    System.out.println("用户" + id + "已被匹配，则退出匹配");
                    return;
                }
                for (String key : matchingHashMap.keySet()) {
                    if (key != id) { //查询到其他正在匹配的用户时 建立房间概念 该房间由先查询到对方的用户建立
                        //1.设置双方状态为匹配完成
                        status = "2";
                        matchingHashMap.get(key).status = "2";

                        //2.设置双方对手信息
                        rivalId = key;
                        matchingHashMap.get(key).rivalId = id;

                        //3.给双方发送提醒信息 匹配成功+对方id
                        session.getBasicRemote().sendText("isMatch" + rivalId);
                        matchingHashMap.get(key).session.getBasicRemote().sendText("isMatch" + id);

                        //4.把双方从匹配池移除
                        matchingHashMap.remove(id);
                        matchingHashMap.remove(key);
                        System.out.println("匹配成功！！！");
                        System.out.println("双方信息为：" + id + " " + key);
                        System.out.println("匹配池剩余人数为：" + matchingHashMap.size());
                        return;
                    }
                }
            }
        } else if (true) { // TODO: 2022/5/18 用户之间的邀请功能 + 当用户在匹配时不可邀请
            
        }


    }

    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session) throws IOException {
        this.session = session;
        this.id = id;
        this.status = "0";
        addOnlineCount();

        //通过id获得用户信息，推送给其他所有用户
        User user = userService.selectById(Integer.parseInt(id));

        //加载其他人的信息 and 把自己的id和用户名推送给匹配大厅的其他人
        for (String key : concurrentHashMap.keySet()) {
            if (key != id) {
                User tmp = userService.selectById(Integer.parseInt(key)); //通过id查询其他用户的用户名
                this.session.getBasicRemote().sendText("已连接:" + key + "&" + tmp.getUsername());
                concurrentHashMap.get(key).session.getBasicRemote().sendText("已连接:" + id + "&" + user.getUsername());
            }
        }

        concurrentHashMap.put(id, this);
        System.out.println("客户端连接：" + this.id);
        System.out.println("匹配大厅人数为：" + onlineCount);
    }

    @OnClose
    public void onClose(@PathParam("id") String id, Session session) throws IOException {
        concurrentHashMap.remove(id);
        subOnlineCount();
        System.out.println("客户端关闭：" + this.id);
        System.out.println("匹配大厅人数为：" + onlineCount);

        //告诉其他人此用户已离开，将此用户从其他人客户端中移除
        User user = userService.selectById(Integer.parseInt(id));
        for (String key : concurrentHashMap.keySet()) {
            if (key != id) {
                concurrentHashMap.get(key).session.getBasicRemote().sendText("已离开:" + id + "&" + user.getUsername());
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MatchWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MatchWebSocket.onlineCount--;
    }

    public static ConcurrentHashMap<String, MatchWebSocket> getWebSocketSet() {
        return concurrentHashMap;
    }

    public static void setWebSocketSet(ConcurrentHashMap<String, MatchWebSocket> webSocketSet) {
        MatchWebSocket.concurrentHashMap = webSocketSet;
    }
}


